#!/bin/bash

# 初始化环境变量
app_service="${app_service:-ssl-service}"
app_service_port="${app_service_port:-80}"
app_container_name="${app_container_name:-ssl-service}"
app_network="${app_network:-server_network}"

config_path=~/web/${app_service}/config
cert_path=~/web/${app_service}/cert

check_container() {
  if docker ps --format '{{.Names}}' | grep -q "^${app_container_name}$"; then
    echo "容器存在!"
    return 0
  else
    echo "容器不存在!"
    return 1
  fi
}

run_service() {
  echo "创建网络"
  echo "docker network create --attachable --driver bridge ${app_network}"
  docker network create --attachable --driver bridge ${app_network} || true

  echo "清理旧容器"
  echo "docker rm -f ${app_container_name}"
  docker rm -f ${app_container_name} || true

  echo "创建配置目录"
  echo "mkdir -p ${config_path}"
  mkdir -p ${config_path}
  echo "mkdir -p ${cert_path}"
  mkdir -p ${cert_path}

  copy_config_files

  echo "启动容器"
  echo "docker run --name ${app_container_name} \
            --network ${app_network} \
            -v ${config_path}:/etc/nginx/conf.d \
            -v ${cert_path}:/etc/nginx/cert \
            -p ${app_service_port}:80 \
            -p 443:443 \
            -d nginx"
  docker run --name ${app_container_name} \
    --network ${app_network} \
    -v ${config_path}:/etc/nginx/conf.d \
    -v ${cert_path}:/etc/nginx/cert \
    -p ${app_service_port}:80 \
    -p 443:443 \
    -d nginx
}

reload_service() {

  copy_config_files

  echo "重启容器"
  echo "docker restart ${app_container_name}"
  docker restart ${app_container_name}
}

clean_service() {
  echo "清除容器"
  echo "docker stop ${app_container_name}"
  docker stop ${app_container_name}
  echo "docker rm ${app_container_name}"
  docker rm ${app_container_name}
}

copy_config_files() {
  echo "复制配置文件"
  echo "cp -R ./release/config/* ${config_path}"
  cp -R ./release/config/* ${config_path}
  echo "cp -R ./release/cert/* ${cert_path}"
  cp -R ./release/cert/* ${cert_path}
}

# 主逻辑
case $1 in
  check)
    check_container
    ;;
  run)
    if check_container; then
      reload_service
    else
      run_service
    fi
    ;;
  rerun)
    clean_service
    run_service
    ;;
  clean)
    clean_service
    ;;
  *)
    echo "Usage: $0 {check|run|rerun|clean}"
    exit 1
    ;;
esac